
import { useState, lazy, Suspense } from 'react'
import { App, Tabs } from 'antd'
import { useMount } from 'ahooks'
import { GetIndexedDB, PutIndexedDB } from '../Utils/IndexedDB'
export const ContentBox = ({ IndexEvent, MenuList }) => {
    const { modal } = App.useApp()
    const [items, setItems] = useState([])
    const [Active, setActive] = useState()

    IndexEvent.useSubscription(async val => {
        const { type, data } = val
        if (type === 'onMenuClick') {
            if (items.findIndex(v => v.key === data) !== -1) onChange(data)
            else {
                console.info(`%c[打开菜单 -- ${data}]`, 'padding: 2px 6px; background: #c4fcd3; color: #f759ab')
                const Temp = lazy(() => import(`../View/AdminItem/${data}.jsx`))
                const { label } = MenuList.find(v => v.key === data)
                const list = [...items, { key: data, label, closable: true, children: <Temp /> }]
                IndexEvent.emit({ type: 'selectMenu', data })
                const openData = [...await GetIndexedDB('openPage'), data]
                await PutIndexedDB('openPage', openData)
                setItems(list)
                setActive(data)
            }
        }
    })

    const onChange = (data) => {
        console.info(`%c[切换菜单 -- ${data}]`, 'padding: 2px 6px; background: #c4fcd3; color: #f759ab')
        IndexEvent.emit({ type: 'selectMenu', data })
        setActive(data)
    }

    const onEdit = async (key) => {
        const targetIndex = items.findIndex(v => v.key === key)
        const list = items.filter(v => v.key !== key)
        setItems(list)
        const openPage = await GetIndexedDB('openPage')
        const newPage = openPage.filter(v => v !== key)
        await PutIndexedDB('openPage', newPage)
        if (key === Active) {
            const data = list[targetIndex === list.length ? targetIndex - 1 : targetIndex]
            onChange(data.key)
        }
    }

    useMount(async () => {
        const open = await GetIndexedDB('open')
        const openPage = await GetIndexedDB('openPage')
        const menu = await GetIndexedDB('menu')
        setActive(open)
        const PageItem = openPage.map(key => {
            const Temp = lazy(() => import(`../View/AdminItem/${key}.jsx`))
            const { rName } = menu.find(v => v.url === key)
            return { key, label: rName, closable: key === 'Home' ? false : true, children: <Temp /> }
        })
        setItems(PageItem)
    })

    return (
        <Suspense
        >
            <div className="ContentBox">
                <Tabs
                    hideAdd
                    items={items}
                    activeKey={Active}
                    type="editable-card"
                    onChange={onChange}
                    onEdit={onEdit}
                />
            </div>
        </Suspense>
    );
}